package leetcode.violence;

public class island {

    public static int countIslands(int[][] m) {
        if (m == null || m[0] == null) {
            return 0;
        }
        int N = m.length;
        int M = m[0].length;
        int res = 0;
        for (int i = 0; i < N; i++) { //遍历行
            for (int j = 0; j < M; j++) {//遍历列
                if (m[i][j] == 1) {//发现一个1
                    res++;//多一个岛
                    infect(m, i, j, N, M);//对这个岛进行感染
                }
            }

        }
        return res;
    }

    public static void infect(int[][] m, int i, int j, int N, int M) {

        if (i < 0 || i >= N || j < 0 || j >= M || m[i][j] != 1) {
            return; //确认i，j没有越界
        }

        m[i][j] = 2;//把这个位置数字改成2
        //递归感染上下左右
        infect(m, i + 1, j, N, M);
        infect(m, i - 1, j, N, M);
        infect(m, i, j + 1, N, M);
        infect(m, i, j - 1, N, M);
    }
}
